/* eslint-disable eqeqeq */
import axios from 'axios'
import { Message } from 'element-ui'
import { getToken, gotoAuthLogin } from '@/utils/auth'
import { isBlob } from './validate'
import { transformBlob } from '@/utils/tools'

// create an axios instance
const service = axios.create({
  baseURL: '', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    config.headers['Authorization'] = getToken() || ''
    config.headers['language'] = `zh`
    config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    // get时 url params endcode
    let url = config.url
    if (config.method === 'get' && config.params) {
      url += '?'
      const keys = Object.keys(config.params)
      for (const key of keys) {
        url += `${key}=${encodeURIComponent(config.params[key])}&`
      }
      url = url.substring(0, url.length - 1)
      config.params = {}
    }
    config.url = url
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  async response => {
    let res = response.data
    if (isBlob(res)) {
      // return
      // res = new Blob([JSON.stringify({ code: 1111, data: {}})], { type: 'application/json' })
      if (res.type === 'application/json') {
        res = await transformBlob(res)
        res = JSON.parse(res)
      } else {
        // console.log(res)
        // return {
        //   res,
        //   params: JSON.parse(response.config.data)
        // }
        res.params = JSON.parse(response.config.data)
        return res
      }
    }
    // console.log(res)
    const status = response.status
    if (status != '200') {
      //
      if (status == '401') {
        // 跳转到登录
        gotoAuthLogin()
      } else {
        return Promise.reject(res)
      }
    } else {
      if (res.code && res.code != 200) {
        if (res.code === '401' || res.code === '403') {
          // 跳转到登录
          gotoAuthLogin()
        } else {
          Message.closeAll()
          Message({
            message: res.msg,
            type: 'error',
            duration: 3 * 1000,
            showClose: true
          })
        }
        return Promise.reject(res)
      } else if (res.code == 200 || !res.code) {
        return res.result || res.data
      }
    }

    // if the custom code is not 20000, it is judged as an error.
  },
  error => {
    console.log('err' + error) // for debug
    Message.closeAll()
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000,
      showClose: true
    })
    return Promise.reject(error)
  }
)

export default service
